<template>
<view>
  <u-sticky :h5-nav-height="0" bg-color="white">
    <view class="sticky-bg">
      <u-navbar title-bold
                :is-fixed="false"
                :titleSize="34"
                :is-back="false"
                :border-bottom="false"
                :background="{background:'white'}"
                title-color="#2F3033"

      >
        <template v-slot:left>
          <view class="back-wrap" @click="uni.$u.route(-1)">
            <image src="/yixu/static/images/dynamic_code/back.png"></image>
            <text>{{formData.id ?'编辑产品':'创建产品'}}</text>
          </view>
        </template>
      </u-navbar>
    </view>
  </u-sticky>
  <view class="form-item">
    <view class="form-item-inner">
      <view class="label-wrap">
        <text class="required">*</text>
        <text>产品名称</text>
      </view>
      <view class="value-wrap">
        <input class="input" v-model="formData.name" placeholder-class="input-pl" placeholder="请输入名称"/>
      </view>
    </view>
  </view>
  <view class="form-item">
    <view class="form-item-inner">
      <view class="label-wrap">
        <text class="required">*</text>
        <text>产品类型</text>
      </view>
      <view class="value-wrap">
      </view>
    </view>
    <view class="extra-wrap">
      <u-radio-group active-color="#165DFF" v-model="formData.type">
        <u-radio :name="1">链接</u-radio>
        <u-radio :name="2">图片</u-radio>
      </u-radio-group>
    </view>
  </view>
  <view class="form-item" v-if="formData.type == 1">
    <view class="form-item-inner">
      <view class="label-wrap">
        <text class="required">*</text>
        <text>链接</text>
      </view>
      <view class="value-wrap">
        <input class="input" v-model="formData.link" placeholder-class="input-pl" placeholder="请输入url链接"/>
      </view>
    </view>
  </view>
  <view class="form-item">
    <view class="form-item-inner">
      <view class="label-wrap">
        <text>产品logo（可不填）</text>
      </view>
      <view class="value-wrap">
      </view>
    </view>
    <view class="extra-wrap">
      <uploader @after-read="(e)=>afterRead('logo',e)"
                :file-list="formData.logo"
                :max-upload="1"
                :deletable="true"
                :mutiple="true"
                @delete="(e)=>handleDelete('logo',e)">

      </uploader>
    </view>
  </view>
  <view class="form-item" v-if="formData.type == 2">
    <view class="form-item-inner">
      <view class="label-wrap">
        <text>产品图片</text>
      </view>
      <view class="value-wrap">
      </view>
    </view>
    <view class="extra-wrap">
      <uploader @after-read="(e)=>afterRead('image',e)"
                :file-list="formData.image"
                :max-upload="1"
                :deletable="true"
                :mutiple="true"
                @delete="(e)=>handleDelete('image',e)">

      </uploader>
    </view>
  </view>
  <view class="btn-wrap">
    <u-button :custom-style="{background:'#165DFF',color:'white',marginBottom:'20rpx'}" @click="onSubmit">提交审核
    </u-button>
    <u-button plain :custom-style="{background:'transparent',color:'#165DFF'}" @click="onDelete" v-if="formData.id">删除</u-button>
  </view>
</view>
</template>

<script>
import {uploadFile} from "../../../utils/tools.js";
import {apiDeleteProduct, apiGetProductDetail, apiSaveProduct} from "../../api/dynamic_code.js";

export default {
  data() {
    return {
      formData: {
        // 添加不用传
        id: '',
        // 产品名称
        name: '',
        // 类型：1-链接；2-图片
        type: 1,
        // 链接：type=1 必传
        link: '',
        //  图片：type=2 必传
        image: [],

        // 产品logo
        logo: [],

      }
    };
  },
  async onLoad({id}) {
    if(id){
      let res = await apiGetProductDetail({id});
      if(res.code == 1){
        let data = res.data;
        this.formData.id = id;
        this.formData.name = data.name;
        this.formData.type = data.type;
        this.formData.link = data.link;
        this.formData.image = [{url:data.image}];
        this.formData.logo =  [{url:data.logo}];
      }
    }
  },
  methods: {
    async onSubmit() {
      let d = {...this.formData};

      if (d.image.length > 0) {
        d.image = d.image[0].url;
      }else{
        d.image = '';
      }
      if (d.logo.length > 0) {
        d.logo = d.logo[0].url;
      }else{
        d.logo = '';
      }
      if (!d.name) {
        uni.$u.toast('请输入产品名称');
        return;
      }
      if (d.type == 1) {
        if (!d.link) {
          uni.$u.toast('请输入url链接');
          return;
        }
        if (!uni.$u.test.url(d.link)) {
          uni.$u.toast('请输入正确的url链接');
          return;
        }
      }
      if (d.type == 2) {
        if (!d.image) {
          uni.$u.toast('请上传产品图片');
          return;
        }
      }
      try {
        uni.showLoading();
        let res = await apiSaveProduct(d);
        if (res.code == 1) {
          uni.$emit('REFRESH_PRODUCT_LIST');
          uni.$u.toast('成功');
          setTimeout(()=>{
            uni.hideLoading();
            uni.navigateBack();
          },1500);
        } else {
          uni.$u.toast(res.msg);
        }
      } finally {
      }
    },
    onDelete() {
      let id = this.formData.id;
      if (!id) {
        uni.$u.toast('产品id不能为空');
        return;
      }
      uni.showModal({
        title: '提示',
        content: '确认删除该产品吗？',
        confirmColor: '#94BFFF',
        confirmText: '确认删除',
        async success(res) {
          if (res.confirm) {
            try {
              uni.showLoading();
              const res = await apiDeleteProduct({id});
              if (res.code == 1) {
                uni.$emit('REFRESH_PRODUCT_LIST');
                uni.$u.toast('删除成功');
                setTimeout(()=>{
                  uni.hideLoading();
                  uni.navigateBack();
                },1500);
              } else {
                uni.$u.toast(res.msg);
              }
            } finally {
              uni.hideLoading();
            }
          }
        }
      })

    },

    afterRead(field, e) {
      const file = e;
      uni.showLoading({
        title: '正在上传中...',
        mask: true
      });
      file.forEach(item => {
        uploadFile(item.path).then(res => {
          uni.hideLoading();
          console.log(res);
          this.formData[field].push(res);
        });
      })
    },
    handleDelete(field, index) {
      this.formData[field].splice(index, 1);
    },
  }
}
</script>

<style lang="scss" scoped>
.btn-wrap {
  padding: 30rpx;
  margin-top: 200rpx;
}

::v-deep .uploader-container .uplader-upload {
  background: #F7F8FA !important;

  .uicon-camera {
    color: #86909C !important;
    position: relative;
    top: -14rpx !important;

    &::after {
      content: '照片';
      position: absolute;
      font-size: 20rpx;
      bottom: -26rpx;
      left: 0;
      right: 0;
      text-align: center;
    }
  }
}

.back-wrap {
  display: flex;
  align-items: center;
  padding-left: 30rpx;
  gap: 10rpx;

  image {
    width: 30rpx;
    height: 30rpx;
  }

  text {
    font-weight: bold;
  }
}

.form-item {
  background: white;
  padding: 20rpx 30rpx;
  margin-top: 5rpx;

  .form-item-inner {
    display: flex;
    align-items: center;
    gap: 30rpx;

  }

  .extra-wrap {
    padding-top: 20rpx;
  }

  .label-wrap {
    color: #1D2129;
    font-size: 30rpx;
    font-weight: 400;
    letter-spacing: 3rpx;

    .required {
      color: red;
    }
  }

  .value-wrap {
    .input {
      font-size: 30rpx;
      color: #1D2129;
    }

    .input-pl {
      color: #C9CDD4;
    }
  }
}
</style>
